package com.ewhale.feitengguest.ui.user.message;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.dto.ConversationDto;
import com.ewhale.feitengguest.presenter.user.message.ChatConversationPresenter;
import com.ewhale.feitengguest.ui.user.message.adapter.TudiAdapter;
import com.ewhale.feitengguest.view.user.message.ChatConversationView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
//import com.hyphenate.easeui.ModelBean;
import com.hyphenate.util.DateUtils;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.simga.library.activity.MBaseFragment;
import com.simga.library.utils.StringUtil;
import com.simga.library.utils.glide.GlideUtil;
import com.simga.library.widget.BGButton;
import com.simga.library.widget.CoustomRefreshView;
import com.simga.library.widget.NListView;
import com.youth.xframe.widget.loadingview.XLoadingView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class ChatConversationFragment extends MBaseFragment<ChatConversationPresenter> implements ChatConversationView {
    @BindView(R.id.iv_avatar)
    ImageView mIvAvatar;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_content)
    TextView mTvContent;
    @BindView(R.id.tv_unRead)
    TextView mTvUnRead;
    @BindView(R.id.ll_master)
    LinearLayout mLlMaster;
    @BindView(R.id.listview)
    NListView mListview;
    @BindView(R.id.tv_time)
    TextView mTvTime;
    @BindView(R.id.tv_tudi)
    TextView mTvTudi;
    @BindView(R.id.ref_layout)
    CoustomRefreshView mRefLayout;
    @BindView(R.id.et_keyWord)
    EditText etKeyWord;
    @BindView(R.id.btn_search)
    BGButton btnSearch;
    @BindView(R.id.xloading_view)
    XLoadingView xloadingView;

    private TudiAdapter mAdapter;
//    private List<ConversationDto.ApprenticeDtoListBean> tudiList;
    private List<ConversationDto.ApprenticeDtoListBean> conversionList;
    protected boolean hidden;
    private ConversationDto conversationDto;

    @Override
    protected int getViewId() {
        return R.layout.fragment_conversion;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        xloadingView.showContent();
        presenter.getConversionList("");
    }

    @Override
    protected void firstInit(Bundle savedInstanceState) {
        conversionList = new ArrayList<>();
        mAdapter = new TudiAdapter(mContext, conversionList);
        mListview.setAdapter(mAdapter);
//        registerReceiver();
        mRefLayout.setEnableLoadmore(false);
    }

    @Override
    protected void initListener() {
        mLlMaster.setOnClickListener(view -> {
            if (conversationDto == null) return;
            if (conversationDto.getMasterDto() == null) return;
            if (conversationDto.getMasterDto().getId() == 0) return;
//            getActivity().sendBroadcast(new Intent("UPDATA_MESSAGE"));
//            IMChatActivity.open(mContext, conversationDto.getMasterDto().getHxId(), conversationDto.getMasterDto().getNickName(), conversationDto.getMasterDto().getHeadPhoto());
        });
        mListview.setOnItemClickListener((adapterView, view, position, l) -> {
//            getActivity().sendBroadcast(new Intent("UPDATA_MESSAGE"));
//            ModelBean bean = tudiList.get(position);
//            IMChatActivity.open(mContext, bean.getHxId(), bean.getNickName(), bean.getAvatar());
        });
        mRefLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                presenter.getConversionList("");
            }
        });
        etKeyWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()) {
                    presenter.getConversionList("");
                }
            }
        });
        btnSearch.setOnClickListener(v -> {
            String keyWord = etKeyWord.getText().toString();
            if (keyWord.isEmpty()) {
                showToast("请输入搜索的昵称/手机号");
                return;
            }
            presenter.getConversionList(keyWord);
        });
    }

    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
    }

    @Override
    public void showConversationList(ConversationDto result, String keyWord) {
        mRefLayout.finishRefreshLoadingMore();
        conversationDto = result;
        refuseMasterInfo();
        //如果徒弟列表为空，则没必要在进行下一步
        if (result.getApprenticeDtoList().size() == 0) {
            xloadingView.showEmpty();
        } else {
            xloadingView.showContent();
            conversionList.clear();
            conversionList.addAll(result.getApprenticeDtoList());
            mAdapter.notifyDataSetChanged();
//            loadConversationList(conversionList);
        }
    }


//    /**
//     * 刷新徒弟聊天列表的信息
//     */
//    private List<ModelBean> modellist;
//
//    public void loadConversationList(List<ConversationDto.ApprenticeDtoListBean> chatList) {
//        modellist = new ArrayList<>();
//        ModelBean modelBean;
//        for (ConversationDto.ApprenticeDtoListBean bean : chatList) {
//            modelBean = new ModelBean();
//            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(bean.getHxId());
//            modelBean.setAvatar(bean.getHeadPhoto());
//            modelBean.setHxId(bean.getHxId());
//            modelBean.setPhone(bean.getPhone());
//            modelBean.setNickName(bean.getNickName());
//            modelBean.setCreateTime(bean.getCreateTime());
//            modelBean.setConversation(conversation);
//            modellist.add(modelBean);
//        }
//        tudiList.clear();
////        ListSort(modellist);
//        tudiList.addAll(modellist);
//        mAdapter.notifyDataSetChanged();
//    }


//    /**
//     * 按照时间进行重新排序
//     *
//     * @param list
//     */
//    private static void ListSort(List<ModelBean> list) {
//        Collections.sort(list, (o1, o2) -> {
//            try {
//                Date dt1 = new Date(o1.getConversation().getLastMessage().getMsgTime());
//                Date dt2 = new Date(o2.getConversation().getLastMessage().getMsgTime());
//                if (dt1.before(dt2)) {
//                    return 1;
//                } else {
//                    return -1;
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            return 0;
//        });
//    }

    public void requestConversion() {
        presenter.getConversionList("");
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        if (!hidden) {
//            loadConversationList(conversionList);
//        }
//    }

//    private void registerReceiver() {
//        IntentFilter filter = new IntentFilter();
//        filter.addAction("UPDATA_MESSAGE");
//        getActivity().registerReceiver(myReceiver, filter);
//    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        getActivity().unregisterReceiver(myReceiver);
//    }

//    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (intent.getAction().equals("UPDATA_MESSAGE")) {
//                if (conversionList != null && conversionList.size() > 0) {
//                    loadConversationList(conversionList);
//                }
//                refuseMasterInfo();
//            }
//        }
//    };

    /**
     * 刷新师父聊天信息
     */
    public void refuseMasterInfo() {
        if (conversationDto.getMasterDto().getId() == 0) {//不存在师父
            mLlMaster.setVisibility(View.GONE);
        } else {
            mLlMaster.setVisibility(View.VISIBLE);
            GlideUtil.loadRoundPicture(conversationDto.getMasterDto().getHeadPhoto(), mIvAvatar, R.drawable.ease_default_avatar);
            mTvName.setText(StringUtil.phone2Unknown(conversationDto.getMasterDto().getPhone()));
            mTvContent.setText("注册时间 ：" + conversationDto.getMasterDto().getCreateTime());
//            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationDto.getMasterDto().getHxId());
//            if (conversation != null) {
//                EMMessage lastMessage = conversation.getLastMessage();
//                if (lastMessage != null) {
//                    mTvUnRead.setVisibility(View.VISIBLE);
//                    mTvTime.setVisibility(View.VISIBLE);
////                    mTvContent.setVisibility(View.VISIBLE);
////                    String content = null;
////                    mTvContent.setText(EaseSmileUtils.getSmiledText(getContext(), EaseCommonUtils.getMessageDigest(lastMessage, (this.getContext()))),
////                            TextView.BufferType.SPANNABLE);
////                    if (content != null) {
////                        mTvContent.setText(content);
////                    }
//                    mTvTime.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime())));
//                    long unRead = conversation.getUnreadMsgCount();
//                    if (unRead > 0) {
//                        mTvUnRead.setText(String.valueOf(unRead));
//                        mTvUnRead.setVisibility(View.VISIBLE);
//                    } else {
//                        mTvUnRead.setVisibility(View.INVISIBLE);
//                    }
//                } else {
//                    mTvUnRead.setVisibility(View.INVISIBLE);
//                    mTvTime.setVisibility(View.INVISIBLE);
////                    mTvContent.setVisibility(View.INVISIBLE);
//                }
//            } else {
//                mTvUnRead.setVisibility(View.INVISIBLE);
//                mTvTime.setVisibility(View.INVISIBLE);
////                mTvContent.setVisibility(View.INVISIBLE);
//            }
        }
    }
}
